module.exports = function(app, settings){
	var log4js 	 = require('log4js')
		, _				 = require('lodash')
		, debug 	 = require('debug')('qywx-api')
		, webRequest  = require('request')
    , template    = require('es6-template-strings')
		, util 		 = require('util')
		, express  = require('express');


	var logger 	    = log4js.getLogger("qywx-api")
		, router 	    = express.Router();


	var GET_JSSDK_URL
		= 'https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=${accessToken}';

  /**
        {
          "errcode":0,
          "errmsg":"ok",
          "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
          "expires_in":7200
        }
   */

  if(!app.locals.jsapiTicket){
    app.locals.jsapiTicket = {};
  }

	router.route('/get_jsapi_ticket')
		.get(function(req, res, next){
			debug("getjsapiticket: ", req.originalUrl);
      var corpId = res.locals.corpId;
      //Check if jsapi_ticket already exist and not expiring
      debug("local cache: ", app.locals.jsapiTicket[corpId] );
      if(app.locals.jsapiTicket[corpId] &&
          app.locals.jsapiTicket[corpId].expiresAt > (_.now() + 5*60*1000)){
        return res.status(200).json({
          success: true,
          data: app.locals.jsapiTicket[corpId]
        });
      }




			var targetUrl = template(GET_JSSDK_URL
						, { accessToken: app.locals.accessToken[corpId].accessToken });

			debug("getuserinfo url: ", targetUrl);


			webRequest.get(targetUrl, function(error, response, body){
				if(error){
					debug("debug - ", error);
					logger.error(error);
					return res.json({
						success: false
						, errors: [{
							code: error.errcode
							, message: error.errmsg
							, internalError: error
						}]
					})
				}
				var data = JSON.parse(body);
				debug(" jsapi_ticket response - ", body);

				if(!data || data.errcode != 0){
					return res.status(500).json({
						success: false,
						errCode: data.errcode,
						errMsg: data.errmsg
					});
				}

        //Cache jsapi_ticket
        app.locals.jsapiTicket[corpId] = {
          expiresAt: _.now() + data.expires_in * 1000,
          ticket: data.ticket
        }
				return res.status(200).json({
          success: true
          ,data: app.locals.jsapiTicket[corpId]
        });
			});
		});

	app.use('/v1/jssdk', router);
}
